import { ref, computed, watch } from "vue";
import { useWindowSize, throttledWatch } from "@vueuse/core";

var stopWatch = null;
export default function (opt = {}) {
  function setHtmlFontSize() {
    document.documentElement.style.fontSize =
      scale.value * option.rootValue + "px";
  }
  function rem2px(rem) {
    const px = ref(0);
    px.value = rem * scale.value * option.rootValue;
    return px;
  }
  function px2rem(px) {
    const rem = ref(0);
    rem.value = scale.value * (px / option.rootValue);
    return rem;
  }
  const option = Object.assign(
    {
      rootValue: 16,
      designWidth: 1920,
      minWidth: 0,
      maxWidth: Infinity
    },
    opt
  );
  const { width } = useWindowSize();
  const _width = computed(() => {
    if (width.value < option.minWidth) {
      return option.minWidth;
    }
    if (width.value > option.maxWidth) {
      return option.maxWidth;
    }
    return width.value;
  });
  const scale = computed(() => {
    const s = _width.value / option.designWidth;
    return s;
  });
  stopWatch?.();
  stopWatch = throttledWatch(width, setHtmlFontSize, {
    throttle: 1000,
    immediate: true
  });
  return {
    rem2px,
    px2rem,
    setHtmlFontSize
  };
}
